﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernateSample.Domain.Entities;

namespace NHibernateSample.DAL
{
    public class TransactionSample
    {
         protected ISession Session{get; set;}

         public TransactionSample(ISession _session)
        {
            Session = _session;
        }

         /// <summary>
         /// Create Customer Transaction
         /// </summary>
         /// <param name="customer"></param>
         /// <returns></returns>
         public int CreateCustomerTransaction(Customer customer)
         {
             using (ITransaction tx = Session.BeginTransaction())
             {
                 try
                 {
                     //一些保存、更新、删除等操作
                     int newId = (int)Session.Save(customer);
                     Session.Flush();
                     tx.Commit();
                     return newId;
                 }
                 catch (HibernateException ex)
                 {
                     tx.Rollback();
                     throw(ex);
                 }
             }
         }

        /// <summary>
         /// Update Customer Transaction
        /// </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
         public void UpdateCustomerTransaction(Customer customer)
         {
             using (ITransaction tx = Session.BeginTransaction())
             {
                 try
                 {
                     Session.Update(customer);
                     Session.Flush();
                     tx.Commit();
                 }
                 catch (HibernateException ex)
                 {
                     tx.Rollback();
                     throw(ex);
                 }
             }
         }

        /// <summary>
         /// Delete Customer Transaction
        /// </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
         public void DeleteCustomerTransaction(Customer customer)
         {
             using (ITransaction tx = Session.BeginTransaction())
             {
                 try
                 {
                     Session.Delete(customer);
                     Session.Flush();
                     tx.Commit();
                 }
                 catch (HibernateException ex)
                 {
                     tx.Rollback();
                     throw(ex);
                 }
             }
         }    
    }
}
